package com.youthburin.utils;

import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

public class FileDownLoadUtils {
	public static void downLoadFile(HttpServletRequest request, HttpServletResponse response, File file)
			throws IOException {
		int fileLength = (int) file.length();
		FileDownLoadRange range = parseRange(request, fileLength);

		response.setContentType("application/force-download");
		response.setContentLength(fileLength);
		response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());

		if (range == null) {
			FileOperateUtils.writeFileToOutputStream(response.getOutputStream(), file, 0, fileLength);
		} else {
			response.setHeader("Accept-Ranges", "bytes");
			response.setHeader("Content-Range", range.getContentRange());
			response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);

			FileOperateUtils
					.writeFileToOutputStream(response.getOutputStream(), file, range.getFirst(), range.getLast());
		}
	}

	private static FileDownLoadRange parseRange(HttpServletRequest request, int fileLength) {
		FileDownLoadRange range = null;
		String rangeStr = request.getHeader("Range");
		if (StringUtils.isNotBlank(rangeStr)) {
			int first = 0, last = 0;
			String[] rangeStrs = rangeStr.split("-");
			if (StringUtils.isNotBlank(rangeStrs[0]) && StringUtils.isNumeric(rangeStrs[0])) {
				first = Integer.valueOf(rangeStrs[0]);
			}
			if (rangeStrs.length >= 2) {
				if (StringUtils.isNotBlank(rangeStrs[1]) && StringUtils.isNumeric(rangeStrs[1])) {
					last = Integer.valueOf(rangeStrs[1]);
				}
			}

			range = new FileDownLoadRange(first, last, fileLength);
		}

		return range;
	}

}
